// 直接引入封装好的API模块
const minLivingAllowance = require('../../../../api/minLivingAllowance.js');
// 引入用户认证工具
const auth = require('../../../../utils/auth');
// 引入加载管理器
const loadingManager = require('../../../../utils/loadingManager');
const pageLoadingManager = require('../../../../utils/pageLoadingManager')
const smartLoadingManager = require('../../../../utils/smartLoadingManager');

console.log('API模块加载完成:', minLivingAllowance);

Page({
  data: {
    // 全局加载状态
    globalLoading: false,
    globalSkeletonType: 'form',
    globalLoadingText: '申请表单加载中...',
    
    // 页面加载状态
    loading: false,
    
    // 表单数据
    form: {
      name: '',
      idCard: '',
      phone: '',
      address: '',
      familySize: '',
      monthlyIncome: '',
      incomeSource: '',
      reason: '',
      idCardImage: '',
      householdImage: '',
      incomeImage: ''
    },
    
    // 收入来源选项
    incomeSources: ['务农收入', '打工收入', '经商收入', '退休金', '低保补助', '其他收入', '无固定收入'],
    incomeSourceIndex: -1,
    
    // 申请声明同意状态
    agreed: false,
    
    // 表单验证状态
    canSubmit: false,

    // 字段错误与展示控制
    errors: {},
    showErrors: false
  },

  // 加载组件准备就绪
  onLoadingReady(e) {
    const loadingInstance = e.detail
    loadingManager.registerLoading('civil-affairs-apply', loadingInstance)
  },

  onLoad(options) {
    console.log('申请页面加载', options);
    
    // 显示页面加载效果
    smartLoadingManager.onPageEnter('pages/service/civil-affairs/apply/index');
    
    // 从用户认证工具获取当前用户信息
    const currentUser = auth.getCurrentUser();
    if (!currentUser) {
      console.warn('用户未登录，请先登录');
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      // 可以跳转到登录页面
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/auth/login/index'
        });
      }, 1500);
      return;
    }
    
    console.log('当前用户信息:', currentUser);
    
    // 验证API模块是否正确加载
    if (minLivingAllowance && minLivingAllowance.submitApplication) {
      console.log('✅ API模块加载成功');
    } else {
      console.error('❌ API模块加载失败');
    }
  },

  onReady() {
    // 页面准备完成，隐藏加载效果
    smartLoadingManager.onPageDataLoaded('pages/service/civil-affairs/apply/index')
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalSkeletonType: data.globalSkeletonType || 'form',
      globalLoadingText: data.globalLoadingText || '申请表单加载中...'
    });
  },


  // 输入框变化处理
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`form.${field}`]: value
    });
  },

  // 收入来源选择器变化处理
  onIncomeSourceChange(e) {
    const { value } = e.detail;
    const incomeSource = this.data.incomeSources[value];
    
    this.setData({
      incomeSourceIndex: value,
      'form.incomeSource': incomeSource
    });
  },

  // 上传身份证照片
  onUploadIdCard() {
    this.chooseAndUploadImage('idCardImage');
  },

  // 上传户口簿照片
  onUploadHousehold() {
    this.chooseAndUploadImage('householdImage');
  },

  // 上传收入证明
  onUploadIncome() {
    this.chooseAndUploadImage('incomeImage');
  },

  // 通用图片选择和上传方法
  async chooseAndUploadImage(fieldName) {
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back'
      });
      
      const tempFilePath = res.tempFiles[0].tempFilePath;
      
      // 显示上传进度
      wx.showLoading({
        title: '上传中...'
      });

      try {
        // 调用真实的上传API
        const uploadResult = await minLivingAllowance.uploadFile(tempFilePath, 'image');
        
        wx.hideLoading();
        
        if (uploadResult && uploadResult.success) {
          // 构建完整的文件URL
          const relativeUrl = uploadResult.data.url;
          const app = getApp();
          const baseUrl = app.globalData?.baseUrl || 'http://localhost:3000';
          const fullUrl = relativeUrl.startsWith('http') ? relativeUrl : `${baseUrl}${relativeUrl}`;
          
          this.setData({
            [`form.${fieldName}`]: fullUrl
          });
          
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          });
        } else {
          throw new Error(uploadResult?.message || '上传失败');
        }
      } catch (uploadError) {
        wx.hideLoading();
        console.error('上传失败:', uploadError);
        wx.showToast({
          title: uploadError.message || '上传失败，请重试',
          icon: 'none',
          duration: 3000
        });
      }
    } catch (err) {
      console.error('选择图片失败', err);
      wx.showToast({
        title: '图片选择失败',
        icon: 'none'
      });
    }
  },

  // 申请声明变化处理
  onDeclarationChange(e) {
    const agreed = e.detail.value.includes('agree');
    this.setData({
      agreed: agreed
    });
  },

  // 表单验证（仅在提交时调用）
  validateForm() {
    const { form, agreed } = this.data;
    
    // 检查必填字段
    const requiredFields = ['name', 'idCard', 'phone', 'address', 'familySize', 'monthlyIncome', 'incomeSource', 'reason'];
    const isBasicInfoValid = requiredFields.every(field => form[field] && form[field].toString().trim());
    
    // 检查必传图片（检查是否包含uploads路径）
    const requiredImages = ['idCardImage', 'householdImage'];
    const isImagesValid = requiredImages.every(field => form[field] && form[field].includes('/uploads/'));
    
    // 检查身份证号格式
    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    const isIdCardValid = form.idCard ? idCardRegex.test(form.idCard) : false;
    
    // 检查手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    const isPhoneValid = form.phone ? phoneRegex.test(form.phone) : false;
    
    const canSubmit = isBasicInfoValid && isImagesValid && isIdCardValid && isPhoneValid && agreed;
    
    // 调试信息
    console.log('表单验证状态:', {
      isBasicInfoValid,
      isImagesValid,
      isIdCardValid,
      isPhoneValid,
      agreed,
      canSubmit,
      formImages: {
        idCardImage: form.idCardImage,
        householdImage: form.householdImage,
        incomeImage: form.incomeImage
      }
    });
    
    const errors = {};
    
    // 必填项缺失
    requiredFields.forEach((field) => {
      if (!form[field] || !form[field].toString().trim()) {
        const fieldNames = {
          name: '姓名',
          idCard: '身份证号',
          phone: '联系电话',
          address: '家庭住址',
          familySize: '家庭人口数',
          monthlyIncome: '家庭月收入',
          incomeSource: '主要收入来源',
          reason: '困难原因'
        };
        errors[field] = `请填写${fieldNames[field]}`;
      }
    });

    // 图片必传
    if (!form.idCardImage || !form.idCardImage.includes('/uploads/')) {
      errors.idCardImage = '请上传身份证照片';
    }
    if (!form.householdImage || !form.householdImage.includes('/uploads/')) {
      errors.householdImage = '请上传户口簿照片';
    }

    // 规则校验
    if (form.idCard && !isIdCardValid) {
      errors.idCard = '身份证号格式不正确';
    }
    if (form.phone && !isPhoneValid) {
      errors.phone = '手机号格式不正确';
    }
    if (!agreed) {
      errors.agreed = '请勾选申请声明';
    }

    this.setData({
      canSubmit,
      errors,
      showErrors: true // 显示错误信息
    });
    
    return canSubmit;
  },

  // 提交申请
  async onSubmit() {
    console.log('开始提交申请...');
    
    // 进行表单验证
    const isValid = this.validateForm();
    
    if (!isValid) {
      wx.showToast({
        title: '请完善申请信息',
        icon: 'none'
      });
      return;
    }

    // 使用自定义加载组件
    this.setData({ loading: true });
    loadingManager.showLoading('civil-affairs-apply', {
      skeletonType: 'form',
      loadingText: '正在提交申请...'
    });

    try {
      // 从用户认证工具获取当前用户信息
      const currentUser = auth.getCurrentUser();
      if (!currentUser) {
        this.setData({ loading: false });
        loadingManager.hideLoading('civil-affairs-apply');
        wx.showToast({
          title: '用户未登录，请重新登录',
          icon: 'none'
        });
        return;
      }
      
      // 准备提交数据
      const { form } = this.data;
      const submitData = {
        userId: parseInt(currentUser.userId),
        applicantName: form.name.trim(),
        applicantIdCard: form.idCard.trim(),
        applicantPhone: form.phone.trim(),
        applicantAddress: form.address.trim(),
        familySize: parseInt(form.familySize),
        monthlyIncome: parseFloat(form.monthlyIncome),
        incomeSource: form.incomeSource,
        difficultyReason: form.reason.trim(),
        idCardImage: form.idCardImage,
        householdImage: form.householdImage,
        incomeProofImage: form.incomeImage || null
      };

      console.log('提交申请数据:', submitData);

      // 调用API方法
      const result = await minLivingAllowance.submitApplication(submitData);
      
      console.log('API返回结果:', result);
      
      this.setData({ loading: false });
      loadingManager.hideLoading('civil-affairs-apply');
      
      if (result && result.success) {
        // 获取申请编号用于显示
        const applicationNo = result.data.applicationNo;
        
        wx.showModal({
          title: '申请提交成功',
          content: `申请编号为：${applicationNo}`,
          showCancel: false,
          confirmText: '确定',
          success: () => {
            // 清空表单数据
            this.resetForm();
            
            // 跳转到我的进度页面，并设置返回页面
            wx.navigateTo({
              url: '/pages/user/progress/index?fromPage=apply'
            });
          }
        });
      } else {
        const errorMessage = result?.message || '提交失败，请重试';
        wx.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
      }
    } catch (error) {
      this.setData({ loading: false });
      loadingManager.hideLoading('civil-affairs-apply');
      console.error('提交申请失败:', error);
      
      let errorMessage = '网络错误，请重试';
      if (error.message) {
        errorMessage = error.message;
      } else if (error.type === 'network') {
        errorMessage = '网络连接失败，请检查网络设置';
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      });
    }
  },

  // 重置表单
  resetForm() {
    this.setData({
      form: {
        name: '',
        idCard: '',
        phone: '',
        address: '',
        familySize: '',
        monthlyIncome: '',
        incomeSource: '',
        reason: '',
        idCardImage: '',
        householdImage: '',
        incomeImage: ''
      },
      incomeSourceIndex: -1,
      agreed: false,
      canSubmit: false,
      errors: {},
      showErrors: false
    });
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: '最低生活保障申请',
      path: '/pages/service/civil-affairs/apply/index'
    };
  }
});